﻿using BaseUtils;
using Service.src.NW.Model;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Service.src.NW.UI
{
    public partial class NWUIGeneratorForm : Form
    {
        public WebView2Handler ViewHandler = null;

        public NWUIGeneratorForm()
        {
            InitializeComponent(); CheckWebView2Runtime(); // 检查运行时
        }

        private void CheckWebView2Runtime()
        {
            if (!Microsoft.Web.WebView2.Core.CoreWebView2Environment.GetAvailableBrowserVersionString().Contains("."))
            {
                // 运行时缺失，提示安装
                var result = MessageBox.Show("未检测到 WebView2 运行时，是否立即安装？", "依赖缺失", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("https://developer.microsoft.com/zh-cn/microsoft-edge/webview2/#download-section");
                }
            }
        }
        public NWUIGeneratorForm(string _url)
        {
           InitializeComponent();
            ViewHandler = new WebView2Handler(NWUIGeneratorView2);
            ViewHandler.uri = _url;
            Icon icon = new Icon("logo.ico");
            this.Icon = icon;
            // NWUIGeneratorView2.Dock = DockStyle.Fill;

            // 表单关闭时仅自身销毁，不影响UI线程的消息循环
            //this.FormClosed += (s, e) => { /* 仅清理自身资源 */ };
        }

        public void Init(string _url)
        {
            ViewHandler = new WebView2Handler(NWUIGeneratorView2);
            ViewHandler.uri = _url;
            Icon icon = new Icon("logo.ico");
            this.Icon = icon;
            NWUIGeneratorView2.Dock = DockStyle.Fill;

            this.Show();
        }
        //private void NWUIGeneratorForm_Load(object sender, EventArgs e)
        //{
        //    //file:///D:/project/number-smart/NW-AUTO-FLOW/NW-AUTO-FLOW/Service/bin/Debug/dist/index.html#/logger
        //    string rqqqqqqqq = BaseService.AppConfig.field.SupplierName == "NWP" ? "file://" + AppData.AppPath + "dist/index.html#/" : $"http://localhost:5173/#/404";
        //    rqqqqqqqq += ViewHandler.uri;
        //    ViewHandler.InitWebView2("http://localhost:5173/#/logger");
        //    //ViewHandler.InitWebView2("http://localhost:5173/#/" + ViewHandler.uri);
        //}
        private async void NWUIGeneratorForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 1. 确保 WebView2 核心初始化完成（关键步骤）
                if (NWUIGeneratorView2.CoreWebView2 == null)
                {
                    // 显示加载提示
                    this.Text = "初始化 WebView2 核心...";

                    // 等待核心初始化（最多等待10秒）
                    var initializationTask = NWUIGeneratorView2.EnsureCoreWebView2Async();
                    if (await Task.WhenAny(initializationTask, Task.Delay(10000)) != initializationTask)
                    {
                        MessageBox.Show("WebView2 核心初始化超时，请检查是否安装了 WebView2 运行时。");
                        return;
                    }
                }

                // 2. 核心初始化成功后再加载 URL
                string url = "https://www.baidu.com"; // 先使用固定URL测试
                NWUIGeneratorView2.Source = new Uri(url);
                this.Text = "加载中...";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败：{ex.Message}\n{ex.StackTrace}");
            }
        }
        private void NWUIGeneratorView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            ViewHandler.MainView_NavigationCompleted(sender, e, NWUIGeneratorView2);
        }
    }
}
